/*
 * @Description: ChatServer - 多线程服务器
 * @Author: rendc
 * @Date: 2025-03-18 14:05:59
 * @LastEditors: rendc
 * @LastEditTime: 2025-03-18 14:53:14
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {

  public static void main(String[] args) throws Exception {
    // 提供一个多线程的服务器 接收多个客户端的连接
    // 1. 搭建服务器端
    int port = 8888;
    ServerSocket server = new ServerSocket(port);
    System.out.println("服务器：启动成功，等待客户端连接，启动的端口是" + port);
    while (true) {
      // 2.接收客户端连接对象
      Socket client = server.accept();
      System.out.println("服务器：客户端连接成功" + client);
      // 3.分离一个子线程 为当前连接的客户端提供服务
      Thread th = new Thread() {
        @Override
        public void run() {
          System.out.println("run方法执行");
          // 获取IO流
          // 输入流 - 来自 客户端的消息
          BufferedReader br = null;
          try {
            br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            // 操作数据
            String line = null;
            while ((line = br.readLine()) != null) {
              System.out.println("服务器：接收到的消息" + line);
            }
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            // 关闭资源
            try {
              if (br != null) {
                br.close();
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
            try {
              if (client != null) {
                client.close();
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
            try {
              if (server != null) {
                server.close();
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
      };
      // 启动线程
      th.start();
    }
  }
}